package com.betterjr.modules.loan.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.data.WebServiceErrorCode;
import com.betterjr.common.exception.BytterTradeException;
import com.betterjr.common.exception.BytterWebServiceException;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterDateUtils;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.DictUtils;
import com.betterjr.common.utils.MathExtend;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.mapper.pagehelper.Page;
import com.betterjr.modules.acceptbill.entity.ScfAcceptBill;
import com.betterjr.modules.acceptbill.service.ScfAcceptBillService;
import com.betterjr.modules.account.service.CustAccountService;
import com.betterjr.modules.agreement.entity.CustAgreement;
import com.betterjr.modules.agreement.entity.ScfRequestCredit;
import com.betterjr.modules.agreement.entity.ScfRequestNotice;
import com.betterjr.modules.agreement.entity.ScfRequestOpinion;
import com.betterjr.modules.agreement.entity.ScfRequestProtacal;
import com.betterjr.modules.agreement.service.ScfAgreementService;
import com.betterjr.modules.agreement.service.ScfFactorRemoteHelper;
import com.betterjr.modules.asset.service.ScfAssetService;
import com.betterjr.modules.credit.entity.ScfCredit;
import com.betterjr.modules.credit.entity.ScfCreditInfo;
import com.betterjr.modules.credit.service.ScfCreditDetailService;
import com.betterjr.modules.credit.service.ScfCreditService;
import com.betterjr.modules.customer.ICustMechBankAccountService;
import com.betterjr.modules.customer.ICustMechBaseService;
import com.betterjr.modules.customer.ICustMechLawService;
import com.betterjr.modules.customer.entity.CustMechBankAccount;
import com.betterjr.modules.customer.entity.CustMechBase;
import com.betterjr.modules.customer.entity.CustMechLaw;
import com.betterjr.modules.enquiry.entity.ScfOffer;
import com.betterjr.modules.enquiry.service.ScfEnquiryService;
import com.betterjr.modules.enquiry.service.ScfOfferService;
import com.betterjr.modules.loan.dao.ScfRequestMapper;
import com.betterjr.modules.loan.entity.ScfLoan;
import com.betterjr.modules.loan.entity.ScfPayPlan;
import com.betterjr.modules.loan.entity.ScfRequest;
import com.betterjr.modules.loan.entity.ScfRequestScheme;
import com.betterjr.modules.loan.entity.ScfServiceFee;
import com.betterjr.modules.loan.helper.RequestLastStatus;
import com.betterjr.modules.loan.helper.RequestTradeStatus;
import com.betterjr.modules.loan.helper.RequestType;
import com.betterjr.modules.order.entity.ScfInvoice;
import com.betterjr.modules.order.entity.ScfOrder;
import com.betterjr.modules.order.helper.ScfOrderRelationType;
import com.betterjr.modules.order.service.ScfOrderService;
import com.betterjr.modules.param.entity.FactorParam;
import com.betterjr.modules.product.entity.ScfProduct;
import com.betterjr.modules.product.service.ScfProductService;
import com.betterjr.modules.productconfig.entity.ScfProductConfig;
import com.betterjr.modules.productconfig.sevice.ScfProductConfigService;
import com.betterjr.modules.receivable.entity.ScfReceivable;
import com.betterjr.modules.template.entity.ScfContractTemplate;
import com.betterjr.modules.template.service.ScfContractTemplateService;
import com.betterjr.modules.workflow.data.CustFlowNodeData;

@Service
public class ScfRequestService extends BaseService<ScfRequestMapper, ScfRequest> {

    @Autowired
    private ScfAcceptBillService scfAcceptService;

    @Autowired
    private ScfPayPlanService payPlanService;
    @Autowired
    private CustAccountService custAccountService;
    @Autowired
    private ScfRequestSchemeService schemeService;
    @Autowired
    private ScfLoanService loanService;
    @Autowired
    private ScfServiceFeeService serviceFeeService;
    @Autowired
    private ScfOrderService orderService;
    @Autowired
    private ScfProductService productService;
    @Autowired
    private ScfProductConfigService productConfigService;
    @Autowired
    private ScfOfferService offerService;
    @Autowired
    private ScfEnquiryService enquiryService;
    @Autowired
    private ScfServiceFeeService feeService;
    @Autowired
    private ScfCreditDetailService creditDetailService;
    @Autowired
    private ScfCreditService scfCreditService;
    @Autowired
    private ScfAgreementService agreementService;
    @Autowired
    private ScfContractTemplateService contractTemplateService;
    @Autowired
    private ScfPayRecordService payRecordService;

    @Autowired
    private ScfAssetService assetService;

    @Reference(interfaceClass = ICustMechLawService.class)
    private ICustMechLawService mechLawService;
    @Reference(interfaceClass = ICustMechBaseService.class)
    private ICustMechBaseService mechBaseService;
    @Reference(interfaceClass = ICustMechBankAccountService.class)
    private ICustMechBankAccountService mechBankAccountService;

    @Autowired
    private ScfFactorRemoteHelper factorRemoteHelper;

    public ScfRequest saveStartRequest(ScfRequest anRequest) {
        // 检查核心企业 在 该保理公司的授信情况
        final ScfCredit coreCredit = scfCreditService.findCredit(anRequest.getCoreCustNo(), anRequest.getCoreCustNo(),
                anRequest.getFactorNo(), anRequest.getCreditMode());
        BTAssert.notNull(coreCredit, "无法获取核心企业授信记录");

        anRequest.setRequestFrom("1");
        anRequest.setFlowStatus("1");
        anRequest = this.addRequest(anRequest);

        if (null != anRequest.getOfferId()) {
            // 从报价过来的要改变报价状态
            offerService.saveUpdateTradeStatus(anRequest.getOfferId(), "3");

            final ScfOffer offer = offerService.selectByPrimaryKey(anRequest.getOfferId());
            // 从报价过来的要改变报价状态
            enquiryService.saveUpdateBusinStatus(offer.getEnquiryNo(), "-2");
        }

        // 关联订单
        orderService.saveInfoRequestNo(anRequest.getRequestType(), anRequest.getRequestNo(), anRequest.getOrders());
        // 冻结订单
        orderService.forzenInfos(anRequest.getRequestNo(), null);

        // 当融资流程启动时,冻结授信额度 add by Liusq 2016-10-20
        final ScfCreditInfo anCreditInfo = new ScfCreditInfo();
        anCreditInfo.setBusinFlag(anRequest.getRequestType());
        anCreditInfo.setBalance(anRequest.getBalance());
        anCreditInfo.setBusinId(Long.valueOf(anRequest.getRequestNo()));
        anCreditInfo.setCoreCustNo(anRequest.getCoreCustNo());
        anCreditInfo.setCustNo(anRequest.getCustNo());
        anCreditInfo.setFactorNo(anRequest.getFactorNo());
        anCreditInfo.setCreditMode(anRequest.getCreditMode());
        anCreditInfo.setRequestNo(anRequest.getRequestNo());
        anCreditInfo.setDescription(anRequest.getDescription());
        creditDetailService.saveFreezeCredit(anCreditInfo);

        return anRequest;
    }

    /**
     * 新增融资申请
     * 
     * @param anRequest
     * @return
     */
    public ScfRequest addRequest(final ScfRequest anRequest) {
        BTAssert.notNull(anRequest, "新增融资申请失败-anRequest不能为空");
        anRequest.init(anRequest);
        anRequest.setCustName(custAccountService.queryCustName(anRequest.getCustNo()));
        anRequest.setRequestDate(BetterDateUtils.getNumDate());
        this.insert(anRequest);

        fillCustName(anRequest);
        return anRequest;
    }

    /**
     * 修改融资申请
     * 
     * @param anRequest
     * @return
     */
    public ScfRequest saveModifyRequest(final ScfRequest anRequest, final String anRequestNo) {
        BTAssert.notNull(anRequest, "修改融资申请失败-anRequest不能为空");

        if (Collections3.isEmpty(selectByProperty("requestNo", anRequestNo))) {
            throw new BytterTradeException(40001, "修改融资申请失败-找不到原数据");
        }

        anRequest.initModify(anRequest);
        anRequest.setRequestNo(anRequestNo);
        this.updateByPrimaryKeySelective(anRequest);
        return anRequest;
    }

    public ScfRequest saveModifyRequest(final ScfRequest anRequest, final Map<String, Object> anValues) {
        BTAssert.notNull(anRequest, "修改融资申请失败-anRequest不能为空");
        anRequest.initModify(anRequest);
        this.updateByExampleSelective(anRequest, anRequest.getRequestNo(), anValues);
        return anRequest;
    }

    /**
     * 修改融资申请
     * 
     * @param anRequest
     * @return
     */
    public ScfRequest saveAutoModifyRequest(final ScfRequest anRequest, final String anRequestNo) {
        BTAssert.notNull(anRequest, "修改融资申请失败-anRequest不能为空");

        if (Collections3.isEmpty(selectByProperty("requestNo", anRequestNo))) {
            throw new BytterTradeException(40001, "修改融资申请失败-找不到原数据");
        }

        anRequest.initModify(anRequest);
        anRequest.setRequestNo(anRequestNo);
        this.updateByPrimaryKeySelective(anRequest);
        return anRequest;
    }

    /**
     * 查询融资申请列表
     * 
     * @param anMap
     * @param anFlag
     * @param anPageNum
     * @param anPageSize
     * @return
     */
    public Page<ScfRequest> queryRequestList(final Map<String, Object> anMap, final int anFlag, final int anPageNum,
            final int anPageSize) {
        final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, 1 == anFlag,
                "regDate desc,regTime desc");
        for (final ScfRequest scfRequest : page) {
            fillCustName(scfRequest);
        }
        return page;
    }

    /**
     * 查询融资申详情
     * 
     * @param anRequestNo
     * @return
     */
    public ScfRequest findRequestDetail(final String anRequestNo) {
        final ScfRequest request = this.selectByPrimaryKey(anRequestNo);
        BTAssert.notNull(request, " 查询融资申详情失败-requestNo不能为空");
        if (null == request) {
            logger.debug("没查到相关数据！");
            return new ScfRequest();
        }

        this.fillCustName(request);

        // 设置还款计划
        request.setPayPlan(payPlanService.findPayPlanByRequest(anRequestNo));

        return request;
    }

    /**
     * 根据申请单号查询申请单信息
     * 
     * @param anRequestNo
     * @return
     */
    public ScfRequest findRequestByRequestNo(final String anRequestNo) {
        final ScfRequest request = this.selectByPrimaryKey(anRequestNo);
        if (null == request) {
            logger.debug("没查到相关数据！");
            return new ScfRequest();
        }
        return request;
    }

    public void fillCustName(final ScfRequest request) {
        // 设置相关名称
        request.setCoreCustName(custAccountService.queryCustName(request.getCoreCustNo()));
        request.setFactorName(custAccountService.queryCustName(request.getFactorNo()));
        final ScfProduct product = productService.findProductById(request.getProductId());
        if (null != product) {
            request.setProductName(product.getProductName());
        }

        if (StringUtils.isBlank(request.getProductName())) {
            final ScfProductConfig productConfig = productConfigService.selectByPrimaryKey(request.getProductId());
            if (null != productConfig) {
                request.setProductName(productConfig.getProductName());
            }
        }

        final ScfServiceFee serviceFee = feeService.findServiceFeeByType(request.getRequestNo(), "1");
        if (null != serviceFee) {
            request.setServicefeeBalance(serviceFee.getBalance());
        }
    }

    /**
     * 资方-出具融资方案（生成应收账款转让通知书/保兑仓业务三方合作协议）
     * 
     * @param anMap
     * @return
     */
    public ScfRequestScheme saveOfferScheme(final ScfRequestScheme anScheme) {
        // 将融资确认后的融资信息放入到申请表中（修改申请表中的信息）
        final ScfRequest request = this.selectByPrimaryKey(anScheme.getRequestNo());
        request.setApprovedPeriod(anScheme.getApprovedPeriod());
        request.setApprovedPeriodUnit(anScheme.getApprovedPeriodUnit());
        request.setManagementRatio(anScheme.getApprovedManagementRatio());
        request.setApprovedRatio(anScheme.getApprovedRatio());
        request.setServicefeeRatio(anScheme.getServicefeeRatio());
        request.setApprovedBalance(anScheme.getApprovedBalance());
        request.setConfirmBalance(anScheme.getApprovedBalance());
        this.saveModifyRequest(request, anScheme.getRequestNo());

        // 1,订单，2:票据;3:应收款;4:经销商
        if (StringUtils.equals(RequestType.SELLER.getCode(), request.getRequestType())) {
            // 生成-保兑仓业务三方合作协议
            agreementService.transProtacal(this.getProtacal(request));
        } else {
            // 生成-应收帐款转让通知书
            final ScfRequestNotice noticeRequest = this.getNotice(request);
            final String appNo = agreementService.transNotice(noticeRequest);

            // 添加转让明细（因为在转让申请时就添加了 转让明细，如果核心企业不同意，那明细需要删除，但目前没有做删除这步）
            agreementService.transCredit(this.getCreditList(request), appNo);
        }

        return schemeService.addScheme(anScheme);
    }

    /**
     * 融资方-确认融资方案（确认融资金额，期限，利率，经销商签署-三方协议书）
     * 
     * @param anRequestNo
     * @param anAduitStatus
     * @return
     */
    public ScfRequestScheme saveConfirmScheme(final String anRequestNo, final String anApprovalResult,
            final String anSmsCode) {
        final ScfRequest request = this.findRequestDetail(anRequestNo);
        final ScfRequestScheme scheme = schemeService.findSchemeDetail2(anRequestNo);
        BTAssert.notNull(scheme);
        scheme.setCustAduit(anApprovalResult);

        // 电子合同类型，0：应收账款债权转让通知书，1：买方确认意见，2三方协议书
        final String agreeType = StringUtils.equals(RequestType.SELLER.getCode(), request.getRequestType()) ? "2" : "0";
        if (StringUtils.equals("0", anApprovalResult)) {
            // if(false ==
            // agreementService.sendValidCodeByRequestNo(anRequestNo, agreeType,
            // anSmsCode)){
            // return AjaxObject.newError("操作失败：短信验证码错误").toJson();
            // }
        } else {
            // 取消签约
            agreementService.cancelElecAgreement(anRequestNo, agreeType, "");
        }

        return schemeService.saveModifyScheme(scheme);
    }

    /**
     * 资方-发起贸易背景确认（生成-应收账款转让确认意见确认书 / 三方协议书）
     * 
     * @param anMap
     * @return
     */
    public ScfRequestScheme saveRequestTradingBackgrand(final String anRequestNo, final String anApprovalResult,
            final String anSmsCode) {
        final ScfRequest request = this.findRequestDetail(anRequestNo);
        final ScfRequestScheme scheme = schemeService.findSchemeDetail2(anRequestNo);
        if (StringUtils.equals("0", anApprovalResult) == true) {
            // 1,订单，2:票据;3:应收款;4:经销商
            if (StringUtils.equals(RequestType.SELLER.getCode(), request.getRequestType())) {

                // 签署三方协议
                // if(false ==
                // agreementService.sendValidCodeByRequestNo(anRequestNo, "2",
                // anSmsCode)){
                // return AjaxObject.newError("操作失败：短信验证码错误").toJson();
                // }
            } else {
                // 生成-应收账款转让确认意见确认书
                agreementService.transOpinion(this.getOption(request));
            }

            // 修改融资方案--核心企业确认状态（待确认）
            scheme.setCoreCustAduit("0");
        }

        return schemeService.saveModifyScheme(scheme);
    }

    /**
     * 核心企业-确认贸易背景（签署-应收账款转让确认意见书/三方协议书）
     * 
     * @param anMap
     * @return
     */
    public ScfRequestScheme confirmTradingBackgrand(final String anRequestNo, final String anApprovalResult,
            final String anSmsCode) {
        final ScfRequestScheme scheme = schemeService.findSchemeDetail2(anRequestNo);
        BTAssert.notNull(scheme);

        final ScfRequest request = this.findRequestDetail(anRequestNo);
        // 电子合同类型，0：应收账款债权转让通知书，1：买方确认意见，2三方协议书
        final String agreeType = StringUtils.equals(RequestType.SELLER.getCode(), request.getRequestType()) ? "2" : "1";
        if (StringUtils.equals(anApprovalResult, "0")) {
            // 签署协议
            // if(false ==
            // agreementService.sendValidCodeByRequestNo(anRequestNo, agreeType,
            // anSmsCode)){
            // return AjaxObject.newError("操作失败：短信验证码错误").toJson();
            // }
        } else {
            // 取消签约
            agreementService.cancelElecAgreement(anRequestNo, agreeType, "");
        }

        // 修改核心企业确认状态
        scheme.setCoreCustAduit("1");
        return schemeService.saveModifyScheme(scheme);
    }

    public ScfRequest saveConfirmLoan(final ScfLoan anLoan) {
        final ScfRequest request = this.selectByPrimaryKey(anLoan.getRequestNo());
        BTAssert.notNull(request, "确认放款失败-找不到融资申请单");

        // ---修申请表---------------------------------------------
        request.setLastStatus(RequestLastStatus.REPLAYMENT.getCode());
        request.setActualDate(anLoan.getLoanDate());
        request.setEndDate(anLoan.getEndDate());
        request.setConfirmBalance(anLoan.getLoanBalance());
        request.setLoanBalance(anLoan.getLoanBalance());
        this.saveModifyRequest(request, request.getRequestNo());

        // ---保存还款计划------------------------------------------
        final ScfPayPlan plan = createPayPlan(anLoan.getInterestBalance(), anLoan.getManagementBalance(), request);
        payPlanService.addPayPlan(plan);

        // ---保存手续费----------------------------------------------
        final BigDecimal servicefeeBalance = saveServiceFee(anLoan.getServicefeeBalance(), request);

        // ---保存放款记录------------------------------------------
        anLoan.setInterestBalance(plan.getShouldInterestBalance());
        anLoan.setManagementBalance(plan.getShouldManagementBalance());
        anLoan.setCustNo(request.getCustNo());
        anLoan.setServicefeeBalance(servicefeeBalance);
        anLoan.setFactorNo(request.getFactorNo());
        loanService.addLoan(anLoan);

        // ----占用授信处理----
        this.occupyCredit(anLoan);

        // 修改资产的状态
        // assetService.saveAssignmentAssetToFactory(Long.parseLong(request.getOrders()));

        return request;
    }

    /**
     * 占用授信处理
     */
    private ScfRequest occupyCredit(final ScfLoan anLoan) {
        final ScfRequest request = this.selectByPrimaryKey(anLoan.getRequestNo());
        BTAssert.notNull(request, "确认放款失败-找不到融资申请单");

        // 占用授信额度
        final ScfCreditInfo anCreditInfo = new ScfCreditInfo();
        anCreditInfo.setBalance(request.getLoanBalance());
        anCreditInfo.setBusinId(anLoan.getId());
        anCreditInfo.setCoreCustNo(request.getCoreCustNo());
        anCreditInfo.setCustNo(request.getCustNo());
        anCreditInfo.setFactorNo(request.getFactorNo());
        anCreditInfo.setRequestNo(request.getRequestNo());
        anCreditInfo.setDescription(request.getDescription());

        // 微信
        if (StringUtils.equals("2", request.getRequestFrom())) {
            anCreditInfo.setBusinFlag("2");// 业务类型(1:应收账款融资;2:应收账款票据质押融资;3:预付款融资;)
            anCreditInfo.setCreditMode("1");// 授信方式(1:信用授信(循环);2:信用授信(一次性);3:担保信用(循环);4:担保授信(一次性);)
        } else {// PC端
            anCreditInfo.setBusinFlag(request.getRequestType());
            anCreditInfo.setCreditMode(request.getCreditMode());
        }

        // 2.3版以后的申请编号以“SQ”开头
        if (request.getRequestNo().startsWith("SQ")) {

            // 根据产品判断是否占用授信额度
            final ScfProductConfig product = productConfigService.findProductByCode(request.getProductCode());
            if (product.getBusinId() != null) {
                // TODO 调用根据产品中的业务类型ID，查找业务类型，由业务类型中的授信标识决定是否暂用申请企业授信额度。
                // if(){
                creditDetailService.saveOccupyCustCredit(anCreditInfo);
                // }
            }

            // 由产品中的授信标识决定是否暂用申请企业授信额度。
            if (StringUtils.equals(product.getCoreCredict(), "1")) {
                creditDetailService.saveOccupyCoreCredit(anCreditInfo);
            }

        } else {
            // 2.0时期的方法
            creditDetailService.saveOccupyCredit(anCreditInfo);
        }

        return request;
    }

    private BigDecimal saveServiceFee(BigDecimal servicefeeBalance, final ScfRequest anRequest) {
        if (null == servicefeeBalance) {
            // 计算手续费(按千分之收)
            servicefeeBalance = anRequest.getApprovedBalance().multiply(anRequest.getServicefeeRatio())
                    .divide(new BigDecimal(1000));
        }

        if (servicefeeBalance.compareTo(BigDecimal.ZERO) < 1) {
            return BigDecimal.ZERO;
        }

        final ScfServiceFee serviceFee = new ScfServiceFee();
        serviceFee.setCustNo(anRequest.getCustNo());
        serviceFee.setFactorNo(anRequest.getFactorNo());
        serviceFee.setRequestNo(anRequest.getRequestNo());
        serviceFee.setPayDate(anRequest.getActualDate());
        serviceFee.setBalance(servicefeeBalance);
        serviceFee.setFeeType("1");
        serviceFeeService.addServiceFee(serviceFee);
        return servicefeeBalance;
    }

    private ScfPayPlan createPayPlan(final BigDecimal anInterestBalance, final BigDecimal anManagementBalance,
            final ScfRequest anRequest) {
        final ScfPayPlan plan = new ScfPayPlan();
        plan.setTerm(1);
        plan.setCustNo(anRequest.getCustNo());
        plan.setCoreCustNo(anRequest.getCoreCustNo());
        plan.setFactorNo(anRequest.getFactorNo());
        plan.setRequestNo(anRequest.getRequestNo());
        plan.setStartDate(anRequest.getActualDate());
        plan.setPlanDate(anRequest.getEndDate());
        plan.setRatio(anRequest.getApprovedRatio());
        plan.setManagementRatio(anRequest.getManagementRatio());

        // 计算应还
        plan.setShouldPrincipalBalance(MathExtend.subtract(anRequest.getLoanBalance(), anRequest.getBondBalance()));
        if (null == anInterestBalance) {
            plan.setShouldInterestBalance(payPlanService.getFee(anRequest.getFactorNo(), anRequest.getLoanBalance(),
                    anRequest.getApprovedRatio(), anRequest.getActualDate(), anRequest.getEndDate()));
        } else {
            plan.setShouldInterestBalance(anInterestBalance);
        }

        if (null == anManagementBalance) {
            plan.setShouldManagementBalance(payPlanService.getFee(anRequest.getFactorNo(), anRequest.getLoanBalance(),
                    anRequest.getManagementRatio(), anRequest.getActualDate(), anRequest.getEndDate()));
        } else {
            plan.setShouldManagementBalance(anManagementBalance);
        }

        // 未还
        plan.setSurplusPrincipalBalance(plan.getShouldPrincipalBalance());
        plan.setSurplusInterestBalance(plan.getShouldInterestBalance());
        plan.setSurplusManagementBalance(plan.getShouldManagementBalance());

        // 计算应还未还总额
        final BigDecimal totalBalance = plan.getShouldPrincipalBalance().add(plan.getShouldInterestBalance())
                .add(plan.getShouldManagementBalance());
        plan.setShouldTotalBalance(totalBalance);
        plan.setSurplusTotalBalance(totalBalance);
        return plan;
    }

    /**
     * 查询待批融资 <=150 出具保理方案 - 110 融资方确认方案 - 120 发起融资背景确认 - 130 核心企业确认背景 - 140
     * 放款确认 - 150 完成融资 - 160 放款完成 - 170
     */
    public Page<ScfRequest> queryPendingRequest(final Map<String, Object> anMap, final String anFlag,
            final int anPageNum, final int anPageSize) {
        // 放款前的状态
        anMap.put("LTEtradeStatus", "150");
        final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, "1".equals(anFlag));
        for (final ScfRequest request : page) {
            fillCustName(request);
            // 设置还款计划
            request.setPayPlan(payPlanService.findPayPlanByRequest(request.getRequestNo()));
        }
        return page;
    }

    /**
     * 查询还款融资 >150 <190 出具保理方案 - 110 融资方确认方案 - 120 发起融资背景确认 - 130 核心企业确认背景 - 140
     * 放款确认 - 150 完成融资 - 160 放款完成 - 170
     */
    public Page<ScfRequest> queryRepaymentRequest(final Map<String, Object> anMap, final String anFlag,
            final int anPageNum, final int anPageSize) {
        // 放款后结束前的状态
        anMap.put("GTtradeStatus", "150");
        anMap.put("LTtradeStatus", "190");
        final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, "1".equals(anFlag));
        for (final ScfRequest request : page) {
            fillCustName(request);
            // 设置还款计划
            request.setPayPlan(payPlanService.findPayPlanByRequest(request.getRequestNo()));
        }
        return page;
    }

    /**
     * 查询历史融资 >=190 出具保理方案 - 110 融资方确认方案 - 120 发起融资背景确认 - 130 核心企业确认背景 - 140
     * 放款确认 - 150 完成融资 - 160 放款完成 - 170
     */
    public Page<ScfRequest> queryCompletedRequest(final Map<String, Object> anMap, final String anFlag,
            final int anPageNum, final int anPageSize) {
        // 放款后结束前的状态
        anMap.put("GTEtradeStatus", "190");
        final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, "1".equals(anFlag));
        for (final ScfRequest scfRequest : page) {
            fillCustName(scfRequest);
            // 设置还款计划
            scfRequest.setPayPlan(payPlanService.findPayPlanByRequest(scfRequest.getRequestNo()));
        }
        return page;
    }

    /**
     * 核心企业融资查询 出具保理方案 - 110 融资方确认方案 - 120 发起融资背景确认 - 130 核心企业确认背景 - 140 放款确认 -
     * 150 完成融资 - 160 放款完成 - 170 anBusinStatus - 1：未放款，2：还款中 3.已还款
     */
    public Page<ScfRequest> queryCoreEnterpriseRequest(Map<String, Object> anMap, final String anBusinStatus,
            final String anFlag, final int anPageNum, final int anPageSize) {
        anMap = Collections3.fuzzyMap(anMap, new String[] { "coreCustNo", "custNo", "factorNo" });
        if (StringUtils.isBlank(anBusinStatus)) {
            final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, "1".equals(anFlag));
            for (final ScfRequest request : page) {
                fillCustName(request);
                // 设置还款计划
                request.setPayPlan(payPlanService.findPayPlanByRequest(request.getRequestNo()));
            }
            return page;
        } else {
            switch (anBusinStatus) {
            case "1":
                // 未放款
                return this.queryPendingRequest(anMap, anFlag, anPageNum, anPageSize);
            case "2":
                // 还款中
                return this.queryRepaymentRequest(anMap, anFlag, anPageNum, anPageSize);
            case "3":
                // 已还款
                return this.queryCompletedRequest(anMap, anFlag, anPageNum, anPageSize);
            default:
                final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize,
                        "1".equals(anFlag));
                for (final ScfRequest request : page) {
                    fillCustName(request);
                    // 设置还款计划
                    request.setPayPlan(payPlanService.findPayPlanByRequest(request.getRequestNo()));
                }
                return page;
            }
        }
    }

    public ScfRequest approveRequest(final Map<String, Object> anMap) {
        return null;
    }

    public List<ScfRequestCredit> getCreditList(final ScfRequest anRequest) {
        final List<ScfRequestCredit> creditList = new ArrayList<ScfRequestCredit>();
        final String type = anRequest.getRequestType();
        if (StringUtils.equals(RequestType.ORDER.getCode(), type)
                || StringUtils.equals(RequestType.SELLER.getCode(), type)) {
            final List<ScfOrder> list = (List) orderService.findInfoListByRequest(anRequest.getRequestNo(),
                    RequestType.ORDER.getCode());
            for (final ScfOrder order : list) {
                creditList.addAll(setInvoice(anRequest, order.getInvoiceList(), order.getBalance(), order.getOrderNo(),
                        order.getEndDate(), order.getAgreementList()));
            }
        } else if (StringUtils.equals(RequestType.BILL.getCode(), type)) {
            final List<ScfAcceptBill> list = (List) orderService.findInfoListByRequest(anRequest.getRequestNo(),
                    RequestType.BILL.getCode());
            for (final ScfAcceptBill bill : list) {
                creditList.addAll(setInvoice(anRequest, bill.getInvoiceList(), bill.getBalance(), bill.getBillNo(),
                        bill.getEndDate(), bill.getAgreementList()));
            }
        } else if (StringUtils.equals(RequestType.RECEIVABLE.getCode(), type)) {
            final List<ScfReceivable> list = (List) orderService.findInfoListByRequest(anRequest.getRequestNo(),
                    RequestType.RECEIVABLE.getCode());
            for (final ScfReceivable receivable : list) {
                creditList.addAll(setInvoice(anRequest, receivable.getInvoiceList(), receivable.getBalance(),
                        receivable.getReceivableNo(), receivable.getEndDate(), receivable.getAgreementList()));
            }
        }
        return creditList;
    }

    /**
     * 设置转主明细相关信息
     * 
     * @param request
     * @param anInvoiceList
     * @param anBalance
     * @param anObjectNo
     * @param anAgreement
     * @return
     */
    private List<ScfRequestCredit> setInvoice(final ScfRequest request, final List<ScfInvoice> anInvoiceList,
            final BigDecimal anBalance, final String anObjectNo, final String anEndDate,
            final List<CustAgreement> custAgreementList) {
        final CustAgreement custAgreement = Collections3.getFirst(custAgreementList);// 暂时都取第一个贸易合同信息
        final List<ScfRequestCredit> creditList = new ArrayList<ScfRequestCredit>();
        for (final ScfInvoice invoice : anInvoiceList) {
            final ScfRequestCredit credit = new ScfRequestCredit();
            credit.setTransNo(anObjectNo);
            credit.setRequestNo(request.getRequestNo());
            credit.setBalance(anBalance);
            credit.setInvoiceNo(invoice.getInvoiceNo());
            credit.setInvoiceBalance(invoice.getBalance());
            credit.setEndDate(anEndDate);
            if (custAgreement != null) {
                credit.setAgreeNo(custAgreement.getAgreeNo());
            }
            creditList.add(credit);
        }
        return creditList;
    }

    /**
     * 设置转让通知书相关信息
     * 
     * @param anRequestNo
     * @param anRequest
     * @return
     */
    public ScfRequestNotice getNotice(final ScfRequest anRequest) {
        // TODO 合同名称、 银行账号， 保理公司详细地址
        final CustMechBankAccount bankAccount = mechBankAccountService.findDefaultBankAccount(anRequest.getFactorNo());

        final String noticeNo = BetterDateUtils.getDate("yyyyMMdd") + anRequest.getRequestNo();
        final ScfRequestNotice noticeRequest = new ScfRequestNotice();
        noticeRequest.setRequestNo(anRequest.getRequestNo());
        noticeRequest.setAgreeName(anRequest.getCustName() + "应收账款债权转让通知书");
        // noticeRequest.setNoticeNo(noticeNo);
        noticeRequest.setBuyer(anRequest.getCoreCustName());
        noticeRequest.setFactorRequestNo(noticeNo);
        noticeRequest.setBankAccount(bankAccount.getBankAcco());
        final CustMechBase custBase = mechBaseService.findBaseInfo(anRequest.getFactorNo());
        noticeRequest.setFactorAddr(custBase.getAddress());
        noticeRequest.setFactorPost(custBase.getZipCode());

        // CustMechLaw custMechLaw =
        // mechLawService.findLawInfo(anRequest.getCustNo());
        // noticeRequest.setFactorLinkMan(custMechLaw.getName());
        return noticeRequest;
    }

    /**
     * TODO 设置三方协议相关信息
     * 
     * @return
     */
    public ScfRequestProtacal getProtacal(final ScfRequest anRequest) {
        // 负责人默认为法人
        final String firstJob = "法人";

        final ScfRequestProtacal protacal = new ScfRequestProtacal();
        final CustMechLaw factorLow = mechLawService.findLawInfo(anRequest.getFactorNo());
        final CustMechLaw buyLow = mechLawService.findLawInfo(anRequest.getCoreCustNo());
        final CustMechLaw sellerLow = mechLawService.findLawInfo(anRequest.getCustNo());

        final CustMechBase factorBase = mechBaseService.findBaseInfo(anRequest.getFactorNo());
        final CustMechBase buyBase = mechBaseService.findBaseInfo(anRequest.getCoreCustNo());
        final CustMechBase sellerBase = mechBaseService.findBaseInfo(anRequest.getCustNo());
        protacal.setFirstAddress(factorBase.getAddress());
        protacal.setFirstFax(factorBase.getFax());
        protacal.setFirstNo(anRequest.getFactorNo().toString());
        protacal.setFirstName(anRequest.getFactorName());
        protacal.setFirstJob(firstJob);
        protacal.setFirstPhone(factorBase.getPhone());
        protacal.setFirstLegal(factorLow.getCustName());

        protacal.setSecondAddress(buyBase.getAddress());
        protacal.setSecondFax(buyBase.getFax());
        protacal.setSecondNo(anRequest.getCoreCustNo());
        protacal.setSecondName(anRequest.getCoreCustName());
        protacal.setSecondJob(firstJob);
        protacal.setSecondPhone(buyBase.getPhone());
        protacal.setSecondLegal(buyLow.getCustName());

        protacal.setThreeAddress(sellerBase.getAddress());
        protacal.setThreeFax(sellerBase.getFax());
        protacal.setThreeNo(anRequest.getCustNo());
        protacal.setThreeName(anRequest.getCustName());
        protacal.setThreeJob(firstJob);
        protacal.setThreePhone(sellerBase.getPhone());
        protacal.setThreeLegal(sellerLow.getCustName());
        protacal.setRequestNo(anRequest.getRequestNo());

        final List<CustAgreement> list = orderService.findRelationInfo(anRequest.getRequestNo(),
                ScfOrderRelationType.AGGREMENT);
        protacal.setProtocalNo(Collections3.getFirst(list).getAgreeNo());
        return protacal;
    }

    /**
     * 设置转让意见确认书相关信息
     * 
     * @param anRequest
     * @return
     */
    public ScfRequestOpinion getOption(final ScfRequest anRequest) {
        final String noticeNo = BetterDateUtils.getNumDate() + anRequest.getRequestNo();
        final ScfRequestOpinion opinion = new ScfRequestOpinion();
        opinion.setRequestNo(anRequest.getRequestNo());
        opinion.setFactorRequestNo(noticeNo);
        opinion.setConfirmNo(noticeNo);
        opinion.setSupplier(anRequest.getCustName());
        return opinion;
    }

    public void getDefaultNode(final List<CustFlowNodeData> list) {
        CustFlowNodeData node = new CustFlowNodeData();
        node = list.get(list.size() - 1);
        node.setNodeCustomName(RequestTradeStatus.FINISH_LOAN.getName());

        node = new CustFlowNodeData();
        node.setNodeCustomName(RequestTradeStatus.OVERDUE.getName());
        node.setSysNodeName(RequestTradeStatus.OVERDUE.getName());
        node.setSysNodeId(new Long(RequestTradeStatus.OVERDUE.getCode()));
        node.setId(new Long(RequestTradeStatus.OVERDUE.getCode()));
        list.add(node);

        node = new CustFlowNodeData();
        node.setNodeCustomName(RequestTradeStatus.EXTENSION.getName());
        node.setSysNodeName(RequestTradeStatus.EXTENSION.getName());
        node.setSysNodeId(new Long(RequestTradeStatus.EXTENSION.getCode()));
        node.setId(new Long(RequestTradeStatus.EXTENSION.getCode()));
        list.add(node);

        node = new CustFlowNodeData();
        node.setNodeCustomName(RequestTradeStatus.CLEAN.getName());
        node.setSysNodeName(RequestTradeStatus.CLEAN.getName());
        node.setSysNodeId(new Long(RequestTradeStatus.CLEAN.getCode()));
        node.setId(new Long(RequestTradeStatus.CLEAN.getCode()));
        list.add(node);

        node = new CustFlowNodeData();
        node.setNodeCustomName(RequestTradeStatus.CLOSED.getName());
        node.setSysNodeName(RequestTradeStatus.CLOSED.getName());
        node.setSysNodeId(new Long(RequestTradeStatus.CLOSED.getCode()));
        node.setId(new Long(RequestTradeStatus.CLOSED.getCode()));
        list.add(node);
    }

    /**
     * 填充订单信息
     * 
     * @param anScfRequest
     */
    public Object fillOrderInfo(final ScfRequest anScfRequest) {
        // 经销商融资不用设置
        if (StringUtils.equals(RequestType.SELLER.getCode(), anScfRequest.getRequestType())) {
            return null;
        }

        if (StringUtils.equals(RequestType.ORDER.getCode(), anScfRequest.getRequestType())) {
            final List<ScfOrder> orderList = (List) orderService.findInfoListByRequest(anScfRequest.getRequestNo(),
                    anScfRequest.getRequestType());
            return Collections3.getFirst(orderList);
        } else if (StringUtils.equals(RequestType.BILL.getCode(), anScfRequest.getRequestType())) {
            final List<ScfAcceptBill> orderList = (List) orderService.findInfoListByRequest(anScfRequest.getRequestNo(),
                    anScfRequest.getRequestType());
            return Collections3.getFirst(orderList);
        } else {
            final List<ScfReceivable> orderList = (List) orderService.findInfoListByRequest(anScfRequest.getRequestNo(),
                    anScfRequest.getRequestType());
            return Collections3.getFirst(orderList);
        }

    }

    /**
     * 查询融资列表，无分页
     */
    public List<ScfRequest> findRequestList(final Map<String, Object> anMap) {
        final List<ScfRequest> requestList = this.selectByProperty(anMap);
        for (final ScfRequest request : requestList) {
            fillCustName(request);
        }
        return requestList;
    }

    /**
     * anBusinStatus - 1：未放款，2：还款中 3.已还款
     */
    public Page querySupplierRequestByCore(final Map<String, Object> anQueryConditionMap, final String anBusinStatus,
            final String anFlag, final int anPageNum, final int anPageSize) {
        anQueryConditionMap.put("requestType", new String[] { RequestType.ORDER.getCode(), RequestType.BILL.getCode(),
                RequestType.RECEIVABLE.getCode() });
        return this.queryCoreEnterpriseRequest(anQueryConditionMap, anBusinStatus, anFlag, anPageNum, anPageSize);
    }

    /**
     * anBusinStatus - 1：未放款，2：还款中 3.已还款
     */
    public Page querySellerRequestByCore(final Map<String, Object> anQueryConditionMap, final String anBusinStatus,
            final String anFlag, final int anPageNum, final int anPageSize) {
        anQueryConditionMap.put("requestType", new String[] { RequestType.SELLER.getCode() });
        return this.queryCoreEnterpriseRequest(anQueryConditionMap, anBusinStatus, anFlag, anPageNum, anPageSize);

    }

    public List<Long> findVoucherBatchNo(final String anRequest) {
        final ScfRequest request = this.selectByPrimaryKey(anRequest);
        if (request != null) {
            return scfAcceptService.findBillRelBatchNo(Long.parseLong(request.getBillId()));
        }
        throw new BytterWebServiceException(WebServiceErrorCode.E1004);
    }

    /**
     * 发送申请单状态给保理公司
     * 
     * @param anRequestNo
     *            申请单编号
     * @param anStatus
     *            申请单状态
     */
    public void updateAndSendRequestStatus(final String anRequestNo, final String anStatus) {
        final ScfRequest request = this.selectByPrimaryKey(anRequestNo);
        if (request != null) {
            request.setOutStatus(anStatus);
            this.factorRemoteHelper.sendRequestStatus(request);
            this.updateByPrimaryKey(request);
        } else {
            logger.warn("sendRequestStatus method not find requestNo " + anRequestNo);
        }

    }

    /**
     * 查询申请列表
     * 
     * @param anMap
     * @param anFlag
     * @param anPageNum
     * @param anPageSize
     * @return
     */
    private Page<ScfRequest> selectRequest(final Map<String, Object> anMap, final String anFlag, final int anPageNum,
            final int anPageSize) {
        if (null != anMap.get("lastStatus") && StringUtils.isNotEmpty(anMap.get("lastStatus").toString())) {
            anMap.put("lastStatus", anMap.get("lastStatus").toString().split(","));
        }
        final Page<ScfRequest> page = this.selectPropertyByPage(anMap, anPageNum, anPageSize, "1".equals(anFlag));
        for (final ScfRequest scfRequest : page) {
            this.fillCustName(scfRequest);
            // 如果已放款，设置还款计划
            if (Integer.parseInt(scfRequest.getLastStatus()) > 3) {
                scfRequest.setPayPlan(payPlanService.findPayPlanByRequest(scfRequest.getRequestNo()));
            }
        }
        return page;
    }

    public Page<ScfRequest> queryRequest(Map<String, Object> anMap, final String anFlag, final int anPageNum,
            final int anPageSize) {
        final String[] queryTerm = new String[] { "lastStatus", "custNo", "factorNo", "coreCustNo", "GTErequestDate",
                "LTErequestDate", "GTEactualDate", "LTEactualDate", "requestType", "custType" };
        anMap = Collections3.filterMap(anMap, queryTerm);
        if (UserUtils.supplierUser() || UserUtils.sellerUser()) {
            anMap.put("operOrg", UserUtils.getOperatorInfo().getOperOrg());
        } else if (UserUtils.coreUser()) {
            anMap.put("coreCustNo", UserUtils.getDefCustInfo().getCustNo());
        } else if (UserUtils.factorUser()) {
            if (null == anMap.get("factorNo")) {
                anMap.put("factorNo", UserUtils.getDefCustInfo().getCustNo());
            }
        } else {
            return null;
        }
        return this.selectRequest(anMap, anFlag, anPageNum, anPageSize);
    }

    public ScfContractTemplate getFactoryContactTemplate(final String requestNo, final String tempType) {
        // 获取融资信息
        final ScfRequest request = findRequestDetail(requestNo);
        if (null == request) {
            logger.error("Can't get request information with request no:" + requestNo);
            throw new BytterTradeException(40001, "无法获取融资信息");
        }
        return contractTemplateService.findTemplateByType(request.getFactorNo(), tempType, "1");
    }

    /**
     * 
     * @Title: getFactoryContactTemplate 
     * @Description: 查询详细融资申请
     * @param requestNo
     * @return TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2017年11月10日 下午2:39:32
     */
    public ScfRequest getFactoryContactTemplate(final String requestNo) {
        // 获取融资信息
        final ScfRequest request = findRequestDetail(requestNo);
        if (null == request) {
            logger.error("Can't get request information with request no:" + requestNo);
            throw new BytterTradeException(40001, "无法获取融资信息");
        }
        return request;
    }

    /**
     * 2.3.1-资方-出具融资方案
     * 
     * @param anMap
     * @return
     */
    public ScfRequestScheme saveScheme(final ScfRequestScheme anScheme) {
        // 将融资确认后的融资信息放入到申请表中（修改申请表中的信息）
        final ScfRequest request = this.selectByPrimaryKey(anScheme.getRequestNo());
        request.setApprovedPeriod(anScheme.getApprovedPeriod());
        request.setApprovedPeriodUnit(anScheme.getApprovedPeriodUnit());
        request.setApprovedRatio(anScheme.getApprovedRatio());
        request.setApprovedBalance(anScheme.getApprovedBalance());
        request.setConfirmBalance(anScheme.getApprovedBalance());
        request.setOverdueRatio(anScheme.getOverdueRatio());
        request.setExtensionRatio(anScheme.getExtensionRatio());
        this.saveModifyRequest(request, anScheme.getRequestNo());
        return schemeService.addScheme(anScheme);
    }

    /**
     * 
    
     * @Title: queryNotUserIneffectiveInvoice 
     * @Description: 查询待融资放款列表
     * @param anMap 前端参数
     * @param anPageNum 页码  
     * @param anPageSize 页面大小
     * @param flag 统计总数
     * @return 待融资放款列表
     * @throws 
     * @author xuzx
     * @date 2017年11月17日 下午4:30:57
     */
    public List<ScfRequest> queryFinancingLoanList(final Long anFactorNo) {
        final Map<String, Object> anMap = new HashMap<String, Object>();
        anMap.put("factorNo", anFactorNo);
        anMap.put("lastStatus", 3);
        final List<ScfRequest> list = this.selectByProperty(anMap);
        return list;
    }

    /**
     * 
     * @Title: queryFinancingLoan 
     * @Description: 查询待融资放款
     * @param anPageNum 页码
     * @param anPageSize  页面数量
     * @param anFlag    是否统计总数
     * @return 分页查询待融资放款
     * @throws 
     * @author xuzx
     * @date 2017年11月20日 下午2:51:58
     */
    public Page<ScfRequest> queryFinancingLoan(final Long anFactorNo, final int anPageNum, final int anPageSize,
            final int flag) {
        final Map<String, Object> anMap = new HashMap<String, Object>();
        anMap.put("factorNo", anFactorNo);
        anMap.put("lastStatus", 3);
        final List<ScfRequest> list = this.selectByProperty(anMap);
        return this.selectPropertyByPage(anMap, anPageNum, anPageSize, flag == 1, "requestNo desc");
    }

    /* @Title: queryStatisticFutureRepayment 
    * @Description: TODO(统计资金方未来十二个月每月回款总金额) 
    * @param @param anMap
    * @param @return 参数说明 
    * @return Map<String,Object> 返回类型 
    * @throws 
    * @author chenlq
    * @date 2017年11月22日 下午8:13:16
    */

    public Map<String, Object> queryStatisticFutureRepayment(Map<String, Object> anMap) {
        BTAssert.notNull(anMap, "查询条件不能为空！");
        // 记录当前日期，包括本月后的十二个月
        String currentDate = anMap.get("currentDate").toString();
        String currentMonthLastDay = getLastDayOfMonth(currentDate);
        final String factorNo = anMap.get("factorNo").toString();
        int monthValue = 0;
        final Map<String, Object> statisticMap = new HashMap<>();
        BigDecimal firstMonthTotalBalance = new BigDecimal(0);
        BigDecimal twoMonthTotalBalance = new BigDecimal(0);
        BigDecimal threeMonthTotalBalance = new BigDecimal(0);
        BigDecimal fourMonthTotalBalance = new BigDecimal(0);
        BigDecimal fiveMonthTotalBalance = new BigDecimal(0);
        BigDecimal sixMonthTotalBalance = new BigDecimal(0);
        BigDecimal sevenMonthTotalBalance = new BigDecimal(0);
        BigDecimal eightMonthTotalBalance = new BigDecimal(0);
        BigDecimal nineMonthTotalBalance = new BigDecimal(0);
        BigDecimal tenMonthTotalBalance = new BigDecimal(0);
        BigDecimal elevenMonthTotalBalance = new BigDecimal(0);
        BigDecimal twelveMonthTotalBalance = new BigDecimal(0);

        // 统计十二个月的金额数据
        for (int i = 0; i < 12; i++) {
            if (i == 0) {
                firstMonthTotalBalance = firstMonthTotalBalance
                        .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                statisticMap.put("1", firstMonthTotalBalance);
            }
            if (i != 0) {
                currentDate = currentDate.substring(0, 4) + (Integer.parseInt(currentDate.substring(4, 6)) + 1) + "01";
                monthValue = Integer.parseInt(currentDate.substring(4, 6));
                if (monthValue > 12 && currentDate.length() == 8) {

                    currentDate = Integer.parseInt(currentDate.substring(0, 4)) + 1 + "0101";
                }
                if (currentDate.length() == 7) {
                    currentDate = currentDate.substring(0, 4) + "0" + currentDate.substring(4, 7);
                }
                // 得到当月的最后一天
                currentMonthLastDay = getLastDayOfMonth(currentDate);
                if (i == 1) {
                    twoMonthTotalBalance = twoMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 2) {
                    threeMonthTotalBalance = threeMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 3) {
                    fourMonthTotalBalance = fourMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 4) {
                    fiveMonthTotalBalance = fiveMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 5) {
                    sixMonthTotalBalance = sixMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 6) {
                    sevenMonthTotalBalance = sevenMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 7) {
                    eightMonthTotalBalance = eightMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 8) {
                    nineMonthTotalBalance = nineMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 9) {
                    tenMonthTotalBalance = tenMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 10) {
                    elevenMonthTotalBalance = elevenMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                } else if (i == 11) {
                    twelveMonthTotalBalance = twelveMonthTotalBalance
                            .add(StatisticEveryMonthBalance(factorNo, currentDate, currentMonthLastDay));
                }
            }
        }
        // 记录下未来十二个月的回款情况
        statisticMap.put("2", twoMonthTotalBalance);
        statisticMap.put("3", threeMonthTotalBalance);
        statisticMap.put("4", fourMonthTotalBalance);
        statisticMap.put("5", fiveMonthTotalBalance);
        statisticMap.put("6", sixMonthTotalBalance);
        statisticMap.put("7", sevenMonthTotalBalance);
        statisticMap.put("8", eightMonthTotalBalance);
        statisticMap.put("9", nineMonthTotalBalance);
        statisticMap.put("10", tenMonthTotalBalance);
        statisticMap.put("11", elevenMonthTotalBalance);
        statisticMap.put("12", twelveMonthTotalBalance);
        return statisticMap;
    }

    /**
     * 
     * @Title: queryStatisticCoreEnterpriseFuturePayment 
     * @Description: TODO(统计出核心企业未来十二个月的付款金额) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return Map<String,Object> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月29日 下午5:22:33
     */
    public Map<String, Object> queryStatisticCoreEnterpriseFuturePayment(Map<String, Object> anMap) {
        BTAssert.notNull(anMap, "查询条件不能为空！");
        BTAssert.notNull(anMap.get("coreCustNo"), "核心企业编号不能为空！");
        final String coreCustNo = anMap.get("coreCustNo").toString();
        // 记录当前日期，包括本月后的十二个月
        String currentDate = anMap.get("currentDate").toString();
        String currentMonthLastDay = getLastDayOfMonth(currentDate);
        int monthValue = 0;
        final Map<String, Object> statisticMap = new HashMap<>();
        BigDecimal firstMonthTotalBalance = new BigDecimal(0);
        BigDecimal twoMonthTotalBalance = new BigDecimal(0);
        BigDecimal threeMonthTotalBalance = new BigDecimal(0);
        BigDecimal fourMonthTotalBalance = new BigDecimal(0);
        BigDecimal fiveMonthTotalBalance = new BigDecimal(0);
        BigDecimal sixMonthTotalBalance = new BigDecimal(0);
        BigDecimal sevenMonthTotalBalance = new BigDecimal(0);
        BigDecimal eightMonthTotalBalance = new BigDecimal(0);
        BigDecimal nineMonthTotalBalance = new BigDecimal(0);
        BigDecimal tenMonthTotalBalance = new BigDecimal(0);
        BigDecimal elevenMonthTotalBalance = new BigDecimal(0);
        BigDecimal twelveMonthTotalBalance = new BigDecimal(0);

        // 统计十二个月的金额数据
        for (int i = 0; i < 12; i++) {
            if (i == 0) {
                firstMonthTotalBalance = firstMonthTotalBalance
                        .add(statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                statisticMap.put("1", firstMonthTotalBalance);
            }

            if (i != 0) {
                currentDate = currentDate.substring(0, 4) + (Integer.parseInt(currentDate.substring(4, 6)) + 1) + "01";
                monthValue = Integer.parseInt(currentDate.substring(4, 6));
                if (monthValue > 12 && currentDate.length() == 8) {
                    currentDate = Integer.parseInt(currentDate.substring(0, 4)) + 1 + "0101";
                }
                if (currentDate.length() == 7) {
                    currentDate = currentDate.substring(0, 4) + "0" + currentDate.substring(4, 7);
                }
                currentMonthLastDay = getLastDayOfMonth(currentDate);
                if (i == 1) {
                    twoMonthTotalBalance = twoMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 2) {
                    threeMonthTotalBalance = threeMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 3) {
                    fourMonthTotalBalance = fourMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 4) {
                    fiveMonthTotalBalance = fiveMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 5) {
                    sixMonthTotalBalance = sixMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 6) {
                    sevenMonthTotalBalance = sevenMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 7) {
                    eightMonthTotalBalance = eightMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 8) {
                    nineMonthTotalBalance = nineMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 9) {
                    tenMonthTotalBalance = tenMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 10) {
                    elevenMonthTotalBalance = elevenMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                } else if (i == 11) {
                    twelveMonthTotalBalance = twelveMonthTotalBalance.add(
                            statisticCoreEeterpriseEveryMonthBalance(coreCustNo, currentDate, currentMonthLastDay));
                }
            }
        }
        // 记录下未来十二个月的回款情况
        statisticMap.put("2", twoMonthTotalBalance);
        statisticMap.put("3", threeMonthTotalBalance);
        statisticMap.put("4", fourMonthTotalBalance);
        statisticMap.put("5", fiveMonthTotalBalance);
        statisticMap.put("6", sixMonthTotalBalance);
        statisticMap.put("7", sevenMonthTotalBalance);
        statisticMap.put("8", eightMonthTotalBalance);
        statisticMap.put("9", nineMonthTotalBalance);
        statisticMap.put("10", tenMonthTotalBalance);
        statisticMap.put("11", elevenMonthTotalBalance);
        statisticMap.put("12", twelveMonthTotalBalance);
        return statisticMap;
    }

    /**
     * 
     * @Title: StatisticEveryMonthBalance 
     * @Description: TODO(统计资金未来回款每月金额数据) 
     * @param @param requestNo
     * @param @param currentDate
     * @param @param currentMonthLastDay
     * @param @return 参数说明 
     * @return BigDecimal 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月28日 上午11:48:28
     */
    BigDecimal StatisticEveryMonthBalance(String factorNo, String currentDate, String currentMonthLastDay) {
        if (null != this.mapper.StatisFutrueEveryMonthPayBalance(factorNo, currentDate, currentMonthLastDay)) {
            return this.mapper.StatisFutrueEveryMonthPayBalance(factorNo, currentDate, currentMonthLastDay);
        } else {
            return new BigDecimal(0);
        }
    }

    /**
     * 
     * @Title: StatisticEveryMonthBalance 
     * @Description: TODO(统计核心企业未来每月付款金额) 
     * @param @param requestNo
     * @param @param currentDate
     * @param @param currentMonthLastDay
     * @param @return 参数说明 
     * @return BigDecimal 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月28日 上午11:48:28
     */
    BigDecimal statisticCoreEeterpriseEveryMonthBalance(String coreCustNo, String currentDate,
            String currentMonthLastDay) {
        if (null != this.mapper.statisCoreEnterpriseFutrueEveryMonthPayBalance(coreCustNo, currentDate,
                currentMonthLastDay)) {
            return this.mapper.statisCoreEnterpriseFutrueEveryMonthPayBalance(coreCustNo, currentDate,
                    currentMonthLastDay);
        } else {
            return new BigDecimal(0);
        }
    }

    /**
     * 
     * @Title: queryBalanceMoney 
     * @Description: 计算申请金额 
     * @param list
     * @return TODO(说明)
     * @throws 
     * @author xuzx
     * @date 2017年12月2日 下午5:38:30
     */
    public BigDecimal queryBalanceMoney(final List<ScfRequest> list) {
        BigDecimal totalMoney = new BigDecimal(0);
        BigDecimal sum = new BigDecimal(0);
        for (int i = 0; i < list.size(); i++) {
            totalMoney = list.get(i).getBalance();
            if (totalMoney != null) {
                sum = totalMoney.add(sum);
            }
        }
        return sum;
    }

    /**
     * 
     * @Title: querySecuredLoanList 
     * @Description: 资金方查询已经放款列表
     * @param factorNo 资金方编号
     * @return 资金方查询已经放款金额
     * @throws 
     * @author xuzx
     * @date 2017年11月20日 下午5:20:20
     */
    public List<ScfRequest> querySecuredLoanList(final Long factorNo) {
        final Map<String, Object> anMap = new HashMap<String, Object>();
        anMap.put("factorNo", factorNo);
        // 已放款
        anMap.put("lastStatus", 4);
        return this.selectByProperty(anMap);
    }

    /**
     * 
    
     * @Title: querySecuredLoanMap 
     * @Description: 资金方工作台金额区域展示数据 
     * @param factorNo  资金方编号
     * @return 资金方工作台金额区域展示数据 
     * @throws 
     * @author xuzx
     * @date 2017年11月21日 下午1:57:32
     */
    public Map<String, Object> queryFactoringAmountArea(final Long factorNo) {
        // 资金方宽限日期
        int graceDays = 0;
        final ScfRequest scfRequest = new ScfRequest();
        final Map<String, Object> allMap = new HashMap<String, Object>(8);
        // 已放款
        final Map<String, Object> securedLoanMap = new HashMap<String, Object>(2);
        securedLoanMap.put("factorNo", factorNo);
        securedLoanMap.put("lastStatus", new String[] { "4", "5", "6", "7", "8" });
        final List<ScfRequest> pendingPaymentList = this.selectByProperty(securedLoanMap);
        // 已放款笔数
        allMap.put("securedLoanCount", pendingPaymentList.size());
        // 已放款金额
        allMap.put("securedLoanMoney", queryLoanBalance(pendingPaymentList));
        // 已回款
        final Map<String, Object> backPaymentMap = new HashMap<String, Object>(2);
        backPaymentMap.put("factorNo", factorNo);
        backPaymentMap.put("lastStatus", 8);
        final List<ScfRequest> backPaymentList = this.selectByProperty(backPaymentMap);
        // 已回款笔数
        allMap.put("backPaymentCount", backPaymentList.size());
        // 已回款金额
        allMap.put("backPaymentMoney", queryLoanBalance(backPaymentList));
        // 待回款
        final Map<String, Object> pendingPaymentMap = new HashMap<String, Object>(2);
        pendingPaymentMap.put("factorNo", factorNo);
        pendingPaymentMap.put("lastStatus", new String[] { "4", "5", "6", "7" });
        final List<ScfRequest> pendingPaymenList = this.selectByProperty(pendingPaymentMap);
        // 待回款笔数
        allMap.put("pendingPaymentCount", pendingPaymenList.size());
        // 待回款金额
        allMap.put("pendingPaymentMoney", queryLoanBalance(pendingPaymenList));
        // 已逾期
        // 保理公司资金方宽限日期
        if (DictUtils.loadObject("FactorParam", String.valueOf(factorNo), FactorParam.class) != null) {
            graceDays = DictUtils.loadObject("FactorParam", String.valueOf(factorNo), FactorParam.class).getGraceDays();
        }
        // 当前系统时间-宽限期
        final String graceDate = BetterDateUtils.pastDateStr(-graceDays);
        // 已逾期
        final Map<String, Object> overdueMap = new HashMap<String, Object>(2);
        overdueMap.put("factorNo", factorNo);
        overdueMap.put("lastStatus", 4);
        overdueMap.put("LTEendDate", graceDate);
        final List<ScfRequest> overdueList = this.selectByProperty(overdueMap);
        // 已逾期笔数
        allMap.put("overdueCount", overdueList.size());
        allMap.put("overdueMoney", queryLoanBalance(overdueList));
        // 已逾期金额
        return allMap;

    }

    /**
     * 
     * @Title: pendingPaymentList 
     * @Description: 资金方放款金额 
     * @param list
     * @return TODO(说明)
     * @throws 
     * @author xuzx
     * @date 2017年11月21日 上午10:24:11
     */
    public BigDecimal queryLoanBalance(final List<ScfRequest> list) {
        BigDecimal totalMoney = new BigDecimal(0);
        BigDecimal sum = new BigDecimal(0);
        for (int i = 0; i < list.size(); i++) {
            totalMoney = list.get(i).getLoanBalance();
            if (totalMoney != null) {
                sum = totalMoney.add(sum);
            }
        }
        return sum;
    }

    /**
     * 
    
     * @Title: queryCoreAmountArea 
     * @Description: 核心企业金额统计 
     * @param anMap 前端参数
     * @param coreCustNo 核心企业编号
     * @return 核心企业金额区域相关信息
     * @throws 
     * @author xuzx
     * @date 2017年11月23日 上午10:36:01
     */
    public Map<String, Object> queryCoreAmountArea(final Map<String, Object> anMap, final Long coreCustNo) {
        final ScfRequest scfRequest = new ScfRequest();
        final Map<String, Object> allMap = new HashMap<String, Object>(8);
        // 应付款
        final Map<String, Object> payableMap = new HashMap<String, Object>(2);
        payableMap.put("coreCustNo", coreCustNo);
        payableMap.put("lastStatus", new String[] { "4", "5", "6", "7", "8" });
        final List<ScfRequest> payableList = this.selectByProperty(payableMap);
        // 应付款金额
        allMap.put("payableMoney", queryLoanBalance(payableList));
        // 应付款笔数
        allMap.put("payableCount", payableList.size());
        // 未付款
        final Map<String, Object> unpaidMap = new HashMap<String, Object>(2);
        unpaidMap.put("coreCustNo", coreCustNo);
        unpaidMap.put("lastStatus", new String[] { "4", "5", "6", "7" });
        final List<ScfRequest> unpaidList = this.selectByProperty(unpaidMap);
        // 未付款金额
        allMap.put("unpaidMoney", queryLoanBalance(unpaidList));
        // 未付款笔数
        allMap.put("unpaidCount", unpaidList.size());
        // 逾期
        final Map<String, Object> overdueMap = new HashMap<String, Object>(2);
        final List<ScfRequest> overdueList = new ArrayList<ScfRequest>();
        overdueMap.put("coreCustNo", coreCustNo);
        unpaidMap.put("lastStatus", 4);
        overdueMap.put("NEendDate", "");
        final List<ScfRequest> list = this.selectByProperty(overdueMap);
        for (final ScfRequest request : list) {
            // 保理公司宽限期限
            final int graceDays = DictUtils
                    .loadObject("FactorParam", String.valueOf(request.getFactorNo()), FactorParam.class).getGraceDays();
            // 还款日期
            final int endDate = Integer.parseInt(request.getEndDate());
            // 当前日期
            final int nowDate = Integer.parseInt(BetterDateUtils.getNumDate());
            if (graceDays + endDate < nowDate) {
                overdueList.add(request);
            }
        }
        // 逾期金额
        allMap.put("overdueMoney", queryLoanBalance(overdueList));
        // 逾期笔数
        allMap.put("overdueConut", overdueList.size());
        // 已付总款
        final Map<String, Object> alreadyPaidMap = new HashMap<String, Object>(2);
        alreadyPaidMap.put("coreCustNo", coreCustNo);
        alreadyPaidMap.put("lastStatus", 8);
        final List<ScfRequest> alreadyPaidList = this.selectByProperty(alreadyPaidMap);
        // 已付款金额
        allMap.put("alreadyPaidMoney", queryLoanBalance(alreadyPaidList));
        // 已付款笔数
        allMap.put("alreadyPaidCount", alreadyPaidList.size());
        return allMap;
    }

    /**
     * 
     * @Title: queryCustAmountArea 
     * @Description: 供应商金额信息统计 
     * @param anMap 前端参数
     * @param anCustNo  供应商编号
     * @return 金额信息统计
     * @throws 
     * @author xuzx
     * @date 2017年11月24日 下午1:59:42
     */
    public Map<String, Object> queryCustAmountArea(final Map<String, Object> anMap, final Long anCustNo) {
        final ScfRequest scfRequest = new ScfRequest();
        final Map<String, Object> allMap = new HashMap<String, Object>(8);
        // 待审批总额，笔数
        final Map<String, Object> pendingApprovalMap = new HashMap<String, Object>(2);
        pendingApprovalMap.put("custNo", anCustNo);
        // 申请，审批状态
        pendingApprovalMap.put("lastStatus", new String[] { "1", "2" });
        final List<ScfRequest> pendingApprovalList = this.selectByProperty(pendingApprovalMap);
        allMap.put("pendingApprovalCount", pendingApprovalList.size());
        allMap.put("pendingApprovalMoney", queryBalanceMoney(pendingApprovalList));
        // 已放款
        final Map<String, Object> securedLoanMap = new HashMap<String, Object>(2);
        securedLoanMap.put("custNo", anCustNo);
        // 已放款状态
        securedLoanMap.put("lastStatus", new String[] { "4", "5", "6", "7", "8" });
        final List<ScfRequest> loanList = this.selectByProperty(securedLoanMap);
        allMap.put("securedLoanMoney", queryLoanBalance(loanList));
        allMap.put("securedLoanCount", loanList.size());
        // 已还款，笔数
        final Map<String, Object> repaymentMap = new HashMap<String, Object>(2);
        repaymentMap.put("custNo", anCustNo);
        repaymentMap.put("lastStatus", 8);
        final List<ScfRequest> repaymentList = this.selectByProperty(repaymentMap);
        allMap.put("repaymentMoney", queryLoanBalance(repaymentList));
        allMap.put("repaymentCount", repaymentList.size());
        // 已逾期，笔数
        final Map<String, Object> beOverdueMap = new HashMap<String, Object>(2);
        final List<ScfRequest> beOverdueList = new ArrayList<ScfRequest>();
        beOverdueMap.put("custNo", anCustNo);
        // 放款状态
        beOverdueMap.put("lastStatus", 4);
        beOverdueMap.put("NEendDate", "");
        final List<ScfRequest> list = this.selectByProperty(beOverdueMap);
        for (final ScfRequest scfRequestList : list) {
            // 保理公司宽限期限
            final int graceDays = DictUtils
                    .loadObject("FactorParam", String.valueOf(scfRequestList.getFactorNo()), FactorParam.class)
                    .getGraceDays();
            // 还款日期
            final int endDate = Integer.parseInt(scfRequestList.getEndDate());
            // 当前日期
            final int nowDate = Integer.parseInt(BetterDateUtils.getNumDate());
            if (graceDays + endDate < nowDate) {
                beOverdueList.add(scfRequestList);
            }
        }
        allMap.put("beOverdueMoney", queryLoanBalance(beOverdueList));
        allMap.put("beOverdueCount", beOverdueList.size());
        return allMap;
    }

    /**
    *  @Title: queryStatisticSupplyHistoryFinanceSituation 
    * @Description: TODO(统计供应商过去融资情况，包括应付款和已付款) 
    * @param @param anMap
    * @param @return 参数说明 
    * @return Map<String,Object> 返回类型 
    * @throws 
    * @author chenlq
    * @date 2017年11月24日 上午9:58:55
    */

    public Map<String, Object> queryStatisticSupplyHistoryFinanceSituation(Map<String, Object> anMap) {
        BTAssert.notNull(anMap, "查询条件不能为空！");
        // 记录当前日期，包括本月过去的十二个月
        String currentDate = anMap.get("currentDate").toString();
        String currentMonthLastDay = getLastDayOfMonth(currentDate);
        final String custNo = anMap.get("custNo").toString();
        final String[] month = { "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1" };
        int monthValue = 0;
        // 统计融资申请金额
        final Map<String, Object> statisticFinanceSupplyBalanceMap = new HashMap<>();
        // 统计融资放款金额
        final Map<String, Object> statisticFinanceLoadBalanceMap = new HashMap<>();
        // 记录申请和放款
        final Map<String, Object> statisticSupplyAndLoadMap = new HashMap<>();

        for (int i = 0; i < month.length; i++) {
            if (i == 0) {
                statisticFinanceSupplyBalanceMap.put(month[i], this.mapper.statisticSupplyBeyondEveryMonthpayment(
                        currentDate.substring(0, 6) + "01", currentDate, custNo));
                System.out.println(currentDate.substring(0, 6) + "01");
                statisticFinanceLoadBalanceMap.put(month[i], this.mapper.statisticSupplyBeyondEveryMonthLoadBalance(
                        currentDate.substring(0, 6) + "01", currentDate, custNo));
            }
            if (i != 0) {
                currentDate = currentDate.substring(0, 4) + (Integer.parseInt(currentDate.substring(4, 6)) - 1) + "01";
                monthValue = Integer.parseInt(currentDate.substring(4, 6));
                if (monthValue < 1) {

                    currentDate = Integer.parseInt(currentDate.substring(0, 4)) - 1 + "1201";
                }
                if (currentDate.length() == 7) {
                    currentDate = currentDate.substring(0, 4) + "0" + currentDate.substring(4, 7);
                }
                currentMonthLastDay = getLastDayOfMonth(currentDate);
                statisticFinanceSupplyBalanceMap.put(month[i],
                        this.mapper.statisticSupplyBeyondEveryMonthpayment(currentDate, currentMonthLastDay, custNo));
                statisticFinanceLoadBalanceMap.put(month[i], this.mapper
                        .statisticSupplyBeyondEveryMonthLoadBalance(currentDate, currentMonthLastDay, custNo));
            }
        }
        statisticSupplyAndLoadMap.put("statisticFinanceSupplyBalanceMap", statisticFinanceSupplyBalanceMap);
        statisticSupplyAndLoadMap.put("statisticFinanceLoadBalanceMap", statisticFinanceLoadBalanceMap);
        return statisticSupplyAndLoadMap;

    }

    /**
     * 
     * @Title: queryStatisticFundAllInformation 
     * @Description: TODO(资金方统计出所有供应商融资情况) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return Map<String,Object> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月29日 上午10:38:36
     */
    public Map<String, Object> queryStatisticFundAllInformation(Map<String, Object> anMap) {
        final Map<String, Object> statisticFundAllMap = new HashMap<String, Object>();
        // 统计资金方未来12个月回款情况
        statisticFundAllMap.put("queryStatisticFutureRepayment", queryStatisticFutureRepayment(anMap));
        // 统计资金方供应商过去十二个月放款及回款情况
        statisticFundAllMap.put("queryStatisticBeforeRepaymentAndLoad",
                payRecordService.queryStatisticBeforeRepaymentAndLoad(anMap));
        // 统计资金方收入来源情况
        statisticFundAllMap.put("queryStatisticTotalBalanceIncome",
                payRecordService.queryStatisticTotalBalanceIncome(anMap));

        return statisticFundAllMap;

    }

    /**
     * 
     * @Title: queryStatisticCoreEnterpriseAllInformation 
     * @Description: TODO(统计出核心企业融资情况) 
     * @param @param anMap
     * @param @return 参数说明 
     * @return Map<String,Object> 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月29日 上午11:08:08
     */
    public Map<String, Object> queryStatisticCoreEnterpriseAllInformation(Map<String, Object> anMap) {
        final Map<String, Object> statisticCoreEnterpriseAllMap = new HashMap<String, Object>();
        // 统计核心企业未来12个月付款情况
        statisticCoreEnterpriseAllMap.put("queryStatisticFutureRepayment",
                queryStatisticCoreEnterpriseFuturePayment(anMap));
        // 统计资金方供应商过去十二个月放款及回款情况
        statisticCoreEnterpriseAllMap.put("queryStatisticBeforeShouldPayAndFinshPay",
                payRecordService.queryStatisticCoreEnterpristBeforeRepaymentAndLoad(anMap));
        return statisticCoreEnterpriseAllMap;

    }

    /**
     * 
     * @Title: getLastDayOfMonth 
     * @Description: TODO(获取指定日期的最后一天) 
     * @param @param date
     * @param @return 参数说明 
     * @return String 返回类型 
     * @throws 
     * @author chenlq
     * @date 2017年11月30日 下午2:03:29
     */
    public String getLastDayOfMonth(String date) {
        final int year = Integer.parseInt(date.substring(0, 4));
        final int month = Integer.parseInt(date.substring(4, 6));
        final Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        final int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        final String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;

    }
}
